package com.dingwen.treasure.websocket.client.listener;

import com.dingwen.treasure.websocket.client.handler.TreasureWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import javax.annotation.Resource;
import javax.servlet.annotation.WebListener;

/**
 * 　ApplicationContextRefreshedListener
 * 　@author dingwen
 * 　@date 2022/8/31
 *
 */
@WebListener
@Component
@Slf4j
public class ApplicationContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {


    @Resource
    private TreasureWebSocketHandler treasureWebSocketHandler;



    /**
     * 定义websocket配置
     *
     * @return
     */
    @Bean(name = "webSocketConnectionManager")
    public WebSocketConnectionManager webSocketConnectionManager() {
        StandardWebSocketClient webSocketClient = new StandardWebSocketClient();
        WebSocketConnectionManager manager = new WebSocketConnectionManager(webSocketClient, treasureWebSocketHandler,
                "ws://127.0.0.1:8080");
        manager.setAutoStartup(true);
        return manager;
    }

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("连接中...");
    }
}
